import * as THREE from "three";

// 旋转动画函数
export function animateRotation(object: THREE.Object3D, axis: "x" | "y" | "z", speed: number) {
    function rotate() {
        requestAnimationFrame(rotate);
        object.rotation[axis] += speed;
    }
    rotate();
}

//物体启动状态
export function animateMaterialColorChange(object: { material: { color: { r: number; g: number; b: number; }; }; }, initialMaterial: { color: { r: number; g: number; b: number; }; }, targetMaterial: { color: { r: number; g: number; b: number; }; }, duration: number, run: number) {
    if (!object) return;

    let startTime: number | null = null;

    function animateColor(time: number) {
        if (!startTime) startTime = time;

        const elapsedTime = time - startTime;
        const fraction = Math.min(elapsedTime / duration, 1);

        // 插值颜色
        if (run === 1) {
            object.material.color.r = THREE.MathUtils.lerp(initialMaterial.color.r, targetMaterial.color.r, fraction);
            object.material.color.g = THREE.MathUtils.lerp(initialMaterial.color.g, targetMaterial.color.g, fraction);
            object.material.color.b = THREE.MathUtils.lerp(initialMaterial.color.b, targetMaterial.color.b, fraction);
        }

        if (fraction < 1) {
            requestAnimationFrame(animateColor);
        }
    }

    if (run === 1) {
        object.material = targetMaterial;
        requestAnimationFrame(animateColor);
    } else {
        object.material = initialMaterial;
    }
}

// 创建并设置液体的固定高度
export function createFixedLiquidLevel(tank: THREE.Object3D, model: THREE.Group, heightRatio: number, color: number = 0x0000ff, opacity: number = 0.5) {
    // 获取罐体的内部尺寸
    const boundingBox = new THREE.Box3().setFromObject(tank);
    const size = new THREE.Vector3();
    boundingBox.getSize(size);

    // 创建液体几何体
    const liquidGeometry = new THREE.CylinderGeometry(size.x / 2, size.x / 2, size.y, 32);
    const liquidMaterial = new THREE.MeshPhongMaterial({ color, opacity, transparent: true });
    const liquidMesh = new THREE.Mesh(liquidGeometry, liquidMaterial);

    // 计算并设置液体的高度
    const liquidHeight = size.y * heightRatio;
    liquidMesh.scale.y = liquidHeight / size.y;
    liquidMesh.position.set(
        boundingBox.min.x + size.x / 2,
        boundingBox.min.y + liquidHeight / 2,
        boundingBox.min.z + size.z / 2
    );

    // 添加液体到模型
    model.add(liquidMesh);
}